import cv2
import os
import sys
import time

# Set camera parameters
cap = cv2.VideoCapture('/dev/video0')
cap.set(cv2.CAP_PROP_FPS, 20)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 480)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 640)
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc("M","J","P","G"))

# Set save path
save_path = os.path.expanduser(sys.argv[1])
# save_path = os.path.expanduser('~/dataset/test')
# save_path = os.path.expanduser('/media/huarsuma/2FEA-9429/dataset/test')

# Set timestamp file name
timestamp_filename = "image_timestamp.txt"

while True:
    # Read frame from camera
    ret, frame = cap.read()
    
    # Check if frame was successfully read
    if not ret:
        break

    cv2.imshow("Camera", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    
    # Get current timestamp
    current_time = time.time_ns()
    
    # Set image name
    image_name = f"{current_time}.jpg"
    
    # Save image
    cv2.imwrite(os.path.join(save_path, image_name), frame)
    
    # Write timestamp to timestamp file
    with open(os.path.join(save_path, timestamp_filename), 'a') as timestamp_file:
        timestamp_file.write(f"{current_time}\n")
        
    
# Release resources
cap.release()

